package liaotian;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class ChatClient extends JFrame{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final int WIDTH=500;
	public static final int HEIGHT=500;
	private JTextArea chatArea;
	private JTextField sendText;
	private Socket socket;
	public ChatClient() {
		initComponents();
		try {
			socket=new Socket("192.168.22.116", 9988);
			ReceiveThread rt=new ReceiveThread(socket, chatArea);
			Thread th=new Thread(rt);
			th.start();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	private void initComponents() {
		setTitle("聊天");
		setSize(WIDTH, HEIGHT);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((screenSize.width-WIDTH)/2, (screenSize.height-HEIGHT)/2);
		chatArea=new JTextArea();
		chatArea.setEditable(false);
		JScrollPane sp=new JScrollPane(chatArea);
		add(sp,BorderLayout.CENTER);		
		JPanel panel=new JPanel();
		panel.setLayout(new BorderLayout());
		add(panel, BorderLayout.SOUTH);
		JButton bt=new JButton("发送");
		bt.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
					String mess=sendText.getText();
					oos.writeObject(mess);
					oos.flush();
					sendText.setText("");
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});
		panel.add(bt,BorderLayout.EAST);
		sendText=new JTextField();
		panel.add(sendText, BorderLayout.CENTER);
	}
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				new ChatClient();
			}
		});
	}
}
